"""
Copyright 2011 Max Ludwig. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY Max Ludwig ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Max Ludwig OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of Max Ludwig.
"""

import os
import subprocess
import shutil
import gtk
import nautilus
import locale
import ConfigParser

class FolderTemplate(nautilus.MenuProvider):

    def __init__(self):
        self.MENU_ITEM_NAME = 'FolderTemplate.MenuItem'
        self.SUBMENU_ITEM_NAME = 'FolderTemplate.SubMenuItem'

        language_file = ConfigParser.ConfigParser({
            'menu_item_label': 'Create from folder template',
            'menu_item_tooltip': 'Create a folder based on a template in the template folder.',
            'submenu_item_tooltip': 'Create a folder based on the template "%s"',
            'submenu_item_empty_label': '-- empty --',
            'submenu_item_empty_tooltip': 'No template folders found in "%s".',
            'rename_dialog_title': 'Name folder'
            })

        self.L = dict(language_file.defaults())

        language_file.read(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'FolderTemplate.lang'))
        for section in language_file.sections():
            if locale.getdefaultlocale()[0] in section:
                self.L = dict(language_file.items(section))
                break

    def response_to_dialog(self, entry, dialog, response):
        dialog.response(response)

    def get_new_folder_name(self, default_name):
        dialog = gtk.Dialog(self.L['rename_dialog_title'], None,
            gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_OK, gtk.RESPONSE_OK))
        entry = gtk.Entry()
        entry.set_text(default_name)
        entry.connect("activate", self.response_to_dialog, dialog, gtk.RESPONSE_OK)
        dialog.vbox.pack_end(entry, True, True, 0)
        dialog.show_all()
        response = dialog.run()
        text = entry.get_text()
        dialog.destroy()
        if response == gtk.RESPONSE_OK:
            return text
        return None

    def submenu_item_activate(self, item, template, directory):
        new_folder_name = os.path.basename(template)
        while True:
            new_folder_name = self.get_new_folder_name(new_folder_name)
            if new_folder_name is None:
                return
            if not os.path.exists(os.path.join(directory, new_folder_name)) and os.sep not in new_folder_name:
                break
        shutil.copytree(template, os.path.join(directory, new_folder_name), ignore=shutil.ignore_patterns('.is_template'))

    def get_background_items(self, window, folder):
        directory = None
        if 'x-nautilus-desktop' in folder.get_uri_scheme():
            # doesn't work in Python <2.7 :(
            # directory = subprocess.check_output(['/usr/bin/xdg-user-dir', 'DESKTOP']).strip()
            directory = subprocess.Popen(['/usr/bin/xdg-user-dir', 'DESKTOP'], stdout=subprocess.PIPE).communicate()[0].strip()
        elif 'file' in folder.get_uri_scheme():
            directory = folder.get_location().get_path()
        if not os.path.isdir(directory):
            return None,
        item = nautilus.MenuItem(self.MENU_ITEM_NAME, self.L['menu_item_label'], self.L['menu_item_tooltip'])
        submenu = nautilus.Menu()
        # doesn't work in Python <2.7 :(
        # template_folder = subprocess.check_output(['/usr/bin/xdg-user-dir', 'TEMPLATES']).strip()
        template_folder = subprocess.Popen(['/usr/bin/xdg-user-dir', 'TEMPLATES'], stdout=subprocess.PIPE).communicate()[0].strip()
        templates_exist = False
        if os.path.isdir(template_folder):
            for entry in os.listdir(template_folder):
                if os.path.isdir(os.path.join(template_folder, entry)):
                    if os.path.isfile(os.path.join(template_folder, entry, '.is_template')):
                        templates_exist = True
                        submenu_item = nautilus.MenuItem(self.SUBMENU_ITEM_NAME + '.' + entry, entry, self.L['submenu_item_tooltip'] % entry)
                        submenu_item.connect('activate', self.submenu_item_activate, os.path.join(template_folder, entry), directory)
                        submenu.append_item(submenu_item)
        if not templates_exist:
            submenu_item = nautilus.MenuItem(self.SUBMENU_ITEM_NAME + '.None', self.L['submenu_item_empty_label'], self.L['submenu_item_empty_tooltip'] % template_folder)
            submenu.append_item(submenu_item)
        item.set_submenu(submenu)
        return item,

